<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增发货单明细')" />
    <th:block th:include="include :: select2-css" />
    <th:block th:include="include :: bootstrap-select-css" />
    <style>
        .preimg{
            width: 70px;height: 70px;
        }
    </style>
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-billHead-add">
            <div class="form-group">    
                <label class="col-sm-3 control-label is-required">单号：</label>
                <div class="col-sm-8">
                    <input name="billNo" id="billNo" class="form-control" th:value="${param.billNo}" readonly type="text" required>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label is-required">款号：</label>
                <div class="col-sm-8">
                    <select id="styleNumber" name="styleNumber"></select>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label is-required">数量：</label>
                <div class="col-sm-8">
                    <input name="quantity" class="form-control" type="number" required>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">单价：</label>
                <div class="col-sm-8">
                    <input name="price" class="form-control" type="number">
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">总价：</label>
                <div class="col-sm-8">
                    <input name="totalPrice" class="form-control" type="number">
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: select2-js" />
    <th:block th:include="include :: bootstrap-select-js" />
    <script th:inline="javascript">
        var prefix = ctx + "goods/billHead"
        $("#form-billHead-add").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                var _sn=$("#styleNumber").val();
                if(_sn==''||_sn=='-' || _sn==null){
                    layer.alert('款号不能为空');
                    return;
                }
                $.operate.save(prefix + "/add", $('#form-billHead-add').serialize());
            }
        }


        var prefixGoods=ctx + "api/goods/selectGoodsByStyleNumber?";
        var options = {
            url: prefixGoods,      // 数据接口url
            pageSize: 10, // 每次加载的数据条数
            value: "styleNumber",  // 下拉框value字段名称   接口返回的id
            name: "name", // 下拉框显示字段名称     接口返回的信息（显示内容）
            selected: []  // 默认选中项，格式：[{id:1,text:"选项1"},{id:2,text:"选项2"}]
        };
        ajaxSelect2("styleNumber",options);

        /**
         * ajax获取select2下拉框数据（带鼠标滚动分页）
         * @param selectId 下拉框id
         * @param options 选项，包含如下字段：
         * url 数据接口url
         * pageSize 每次加载的数据条数
         * name 下拉框显示字段名称
         * value 下拉框value字段名称
         * placeholder 默认显示的文字
         * selected 默认选中项，格式：[{id:1,text:"选项1"},{id:2,text:"选项2"}]
         * formatResult 返回结果回调函数，可以在该回调中，自定义下拉框数据的显示样式，比如：加入图片等
         * templateSelection 选中项回调，该参数必须与formatResult参数搭配使用
         * 注意点1 : 后端接口需返回 data（具体数据）和 total（总页数）两个字段
         * 注意点2 : 两个自定义的回调函数中，必须要把处理结果return回来，如果没有传入formatResult参数，则采用默认的显示样式
         */
        function ajaxSelect2 (selectId,options,formatResult,formatSelected) {
            var value = options["value"];
            var styleNumber = options["name"];
            var flag = (typeof formatResult === "function") ? true : false;
            var select2Option = {
                language: "zh-CN",
                allowClear: true,
                placeholder: options["placeholder"] || "请选择",
                // theme : "classic",
                ajax:{
                    url: options["url"],
                    type: "post",
                    dataType: "json",
                    delay: 250,
                    data: function(params){
                        // 传递到后端的参数
                        return {
                            // 搜索框内输入的内容
                            styleNumber: params.term,           //name是接口入参
                            // 当前页
                            curPage: params.page || 1,   //curPage接口入参
                            // 每页显示多少条记录，默认10条
                            pageSize: options["pageSize"] || 10   //pageSize接口入参
                        };
                    },
                    cache:true,
                    processResults: function (res, params) {
                        //res是接口返回的结果 需要返回total总页数
                        params.page = params.page || 1;
                        var cbData = [];
                        if (flag) {
                            cbData = res.list;
                        } else {
                            var data = res.list;
                            var jsonStr = JSON.stringify(data);
                            if(data!=undefined){
                                var len = data.length;
                                for(var i= 0; i<len; i++){
                                    console.log("for Data:"+JSON.stringify(data[i]))
                                    var option = {"id": data[i][value], "styleNumber": data[i].styleNumber,'name':data[i].name,'imgPath':data[i].imgPath};
                                    cbData.push(option);
                                }
                            }
                        }

                        //console.log("cbData:"+JSON.stringify(cbData))
                        return {
                            results: cbData,
                            pagination: {
                                more: params.page < res.total
                            }
                        };
                    },
                },
                escapeMarkup: function (markup) {
                    // 字符转义处理
                    return markup;
                },
                // 最少输入N个字符才开始检索，如果想在点击下拉框时加载数据，请设置为 0
                minimumInputLength: 4,
                templateResult : function(repo) {// 显示的结果集格式，这里需要自己写css样式，可参照demo
                    // 正在检索，绘制检索结果
                    if (repo.loading)
                        return repo.text;
                    var markup = repo.name;
                    console.log("templateResult,markup:"+markup)
                    //markup += repo.realname;
                    //console.log("XXX:"+JSON.stringify(repo));
                    var imgUrl=ctx + "common/download/resource?resource=" + repo.imgPath;
                    var markup = "<div class='select2-result-repository clearfix'>" + "<div class='select2-result-repository__avatar'><img class='preimg' src='"
                        + imgUrl + "' /></div>" + "<div class='select2-result-repository__meta'>"
                        + "<div class='select2-result-repository__title'>" + repo.name + "</div>";
                    return markup;
                },
                templateSelection : function(repo) {
                    //console.log("templateSelection:"+JSON.stringify(repo))
                    //console.log("templateSelection:"+repo.name);
                    //alert("templateSelection:"+repo.name);
                    $("#proName").val(repo.name)
                    return repo.styleNumber || repo.name;
                }// 列表中选择某一项后显示到文本框的内容
            };
            if (flag) {
                //select2Option.templateResult = formatResult;
                //select2Option.templateSelection = formatSelected;
            }
            var $select =  $("#"+selectId);
            $select.select2(select2Option);
            if (!flag) {
                // 默认选中项设置
                console.log("默认选中项设置")
                var html = '';
                var values = [];
                var selected = options['selected'];
                if (selected) {
                    $.each(selected,function (index,item) {
                        values.push(item.styleNumber);
                        html += '<option value="'+item.styleNumber+'">'+item.styleNumber+'</option>';
                    });
                    $select.append(html);
                    $select.val(values).trigger('change');
                }
            }
        }





    </script>
</body>
</html>